<template>
  <el-card class="list-card">
    <template #header>
      <div class="card-header">
        <div class="header-left">
          <span class="group-name">教师志愿选择</span>
        </div>
        <div class="header-right">
          <el-tag type="info" size="small">最多可选: {{ groupInfo.teacherMax || '-' }}个教师</el-tag>
        </div>
      </div>
    </template>

    <div class="card-body">
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="queryParams" class="search-container" style="margin-bottom: 0">
        <el-form-item label="教师姓名">
          <el-input v-model="queryParams.nickName" placeholder="请输入教师姓名" clearable style="width: 180px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="专业方向">
          <el-input v-model="queryParams.majorField" placeholder="请输入专业方向" clearable style="width: 180px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 筛选结果统计 -->
      <div class="filter-stats">
        <span v-if="filterStats.isFiltered" class="stats-info">
          已筛选 {{ filterStats.filtered }} / {{ filterStats.total }} 位教师
        </span>
        <span v-else class="stats-info">
          共 {{ filterStats.total }} 位教师
        </span>
      </div>

      <!-- 教师列表 -->
      <div class="table-container">
        <el-table v-loading="props.teacherLoading" :data="displayTeacherList" border row-key="teacherId" height="100%">
          <el-table-column label="姓名" align="center" prop="user.nickName" />
          <el-table-column label="所属学院" align="center" prop="user.dept.deptName" show-overflow-tooltip />
          <el-table-column label="研究方向" align="center" prop="majorField" show-overflow-tooltip />
          <el-table-column label="邮箱" align="center" prop="email" />
          <el-table-column label="个人简介" align="center">
            <template #default="{ row }">
              <span style="cursor: pointer; color: var(--el-color-primary)" @click="handleView(row)">查看</span>
            </template>
          </el-table-column>
          <el-table-column label="选择状态" align="center" width="120">
            <template #default="{ row }">
              <el-tag v-if="isTeacherSelected(row.teacherId)" type="success" size="small">第{{ getTeacherOrder(row.teacherId) }}志愿</el-tag>
              <el-tag v-else type="info" size="small">未选择</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="120">
            <template #default="{ row }">
              <el-button
                v-if="!isTeacherSelected(row.teacherId)"
                type="primary"
                link
                size="small"
                @click="handleTeacherSelection(row.teacherId)"
                :disabled="!hasAvailableSlots"
              >
                选择
              </el-button>
              <el-button v-else link type="danger" size="small" @click="handleUnselectTeacher(row.teacherId)">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, computed, watch, getCurrentInstance } from 'vue'

const props = defineProps({
  groupInfo: {
    type: Object,
    default: () => ({})
  },
  teacherList: {
    type: Array,
    default: () => []
  },
  teacherLoading: {
    type: Boolean,
    default: false
  },
  selectedTeachers: {
    type: Array,
    default: () => []
  },
  userProfile: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['select-teacher', 'unselect-teacher', 'view-teacher', 'select-student'])

const { proxy } = getCurrentInstance()

// 查询参数
const queryParams = ref({
  nickName: '',
  majorField: ''
})


// 搜索状态
const isSearched = ref(false)
const filteredList = ref([])

// 显示的教师列表（基于搜索状态）
const displayTeacherList = computed(() => {
  return isSearched.value ? filteredList.value : props.teacherList
})

// 筛选结果统计
const filterStats = computed(() => {
  const total = props.teacherList.length
  const displayed = displayTeacherList.value.length
  const isFiltered = isSearched.value && total > displayed
  return {
    total,
    filtered: displayed,
    isFiltered
  }
})

// 执行筛选逻辑
const performFilter = () => {
  let list = [...props.teacherList]

  // 姓名筛选
  if (queryParams.value.nickName?.trim()) {
    const searchTerm = queryParams.value.nickName.trim().toLowerCase()
    list = list.filter(teacher =>
      teacher.user?.nickName?.toLowerCase().includes(searchTerm) ||
      teacher.user?.userName?.toLowerCase().includes(searchTerm)
    )
  }

  // 专业筛选
  if (queryParams.value.majorField?.trim()) {
    const searchTerm = queryParams.value.majorField.trim().toLowerCase()
    list = list.filter(teacher =>
      teacher.majorField?.toLowerCase().includes(searchTerm)
    )
  }

  filteredList.value = list
}

// 是否还有可用志愿槽位
const hasAvailableSlots = computed(() => {
  const maxSlots = props.groupInfo.teacherMax || 0
  return props.selectedTeachers.length < maxSlots
})

// 获取下一个可用的志愿序号
const getNextVolunteerOrder = () => {
  const maxSlots = props.groupInfo.teacherMax || 0
  const usedOrders = props.selectedTeachers.map(t => t.volunteerOrder)

  for (let i = 1; i <= maxSlots; i++) {
    if (!usedOrders.includes(i)) {
      return i
    }
  }
  return null
}

// 判断教师是否已被选择
const isTeacherSelected = (teacherId) => {
  return props.selectedTeachers.some(t => t.teacherId === teacherId)
}

// 获取教师的志愿顺序
const getTeacherOrder = (teacherId) => {
  const index = props.selectedTeachers.findIndex(t => t.teacherId === teacherId)
  return index + 1
}

// 搜索
const handleQuery = () => {
  performFilter()
  isSearched.value = true
}

// 重置
const resetQuery = () => {
  queryParams.value = {
    nickName: '',
    majorField: ''
  }
  isSearched.value = false
  filteredList.value = []
}

// 选择教师志愿
const handleTeacherSelection = (teacherId) => {
  const teacher = props.teacherList.find(t => t.teacherId === teacherId)
  if (teacher) {
    const volunteerOrder = getNextVolunteerOrder()
    if (volunteerOrder !== null) {
      emit('select-teacher', { teacher, volunteerOrder })
    }
  }
}

// 取消选择教师
const handleUnselectTeacher = (teacherId) => {
  emit('unselect-teacher', teacherId)
}

// 查看教师详情
const handleView = (teacher) => {
  emit('view-teacher', teacher)
}

// 监听教师列表变化
watch(() => props.teacherList, () => {
  // 重置搜索状态
  isSearched.value = false
  filteredList.value = []
})

// 初始化队长选择
const initializeTeamLeader = () => {
  if (!props.userProfile?.student) return

  const currentUser = props.userProfile.student
  // 触发队长选择事件
  emit('select-student', currentUser)
}

// 监听userProfile变化，初始化队长选择
watch(() => props.userProfile, (newProfile) => {
  if (newProfile?.student) {
    initializeTeamLeader()
  }
}, { immediate: true })
</script>

<style scoped>
.list-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-card :deep(.el-card__body) {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.card-body {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.search-container {
  flex-shrink: 0;
}

.filter-stats {
  flex-shrink: 0;
  margin-bottom: 16px;
  padding: 8px 12px;
  background-color: var(--el-color-info-light-9);
  border-radius: 4px;
}

.stats-info {
  font-size: 14px;
  color: var(--el-color-info);
}



.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.group-name {
  font-size: 24px;
  color: var(--el-color-primary);
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
}

.table-container {
  flex: 1;
  overflow: hidden;
  min-height: 0;
}
</style>